package _2工具类;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class GoodDAOImpl implements IGoodDAO {

	Connection conn;
	Statement stmt;

	public void getconnection() throws SQLException {
		// 1. 获取连接
		conn = DbUtils.getConnection();
		// 2. 查询对象
		stmt = conn.createStatement();
	}

	@Override
	public int insert(Good d) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "insert into good value('" + d.getGoodid() + "','" + d.getGoodname() + "','" + d.getGoodprice()
				+ "','" + d.getCid() + "')";
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public int deleteById(int goodid) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "delete from good where goodid=" + goodid;
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public int update(Good d) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "update category set goodname='" + d.getGoodname() + "' , goodprice = '" + d.getGoodprice()
				+ "',cid = '" + d.getCid() + "'" + " where goodid=" + d.getGoodid();
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public Good findById(int goodid) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "select * from good where goodid=" + goodid;
		ResultSet rs = stmt.executeQuery(sql);
		Good result = null;
		if (rs.next()) {
			int id = rs.getInt(1);
			String goodname = rs.getString(2);
			double goodprice = rs.getDouble(3);
			int cid = rs.getInt(4);
			result = new Good(id, goodname, goodprice, cid);
		}
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, rs);
		return result;
	}

	@Override
	public List<Good> findAll() throws SQLException {
		// TODO Auto-generated method stub
		List<Good> result = new ArrayList<>();
		getconnection();
		// 3. 执行查询
		String sql = "select * from good";
		ResultSet rs = stmt.executeQuery(sql);
		while (rs.next()) {
			int id = rs.getInt(1);
			String goodname = rs.getString(2);
			double goodprice = rs.getDouble(3);
			int cid = rs.getInt(4);
			Good c = new Good(id, goodname, goodprice, cid);
			result.add(c);
		}
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, rs);
		return result;
	}

}
